﻿using System;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Util;

public partial class Pages_UnitUpdate : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("ADMIN"))
        {
            if (!IsPostBack)
            {
                FillDdlState();
                FillData();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    private void FillDdlPlace()
    {
        PlaceController placeController = new PlaceController();
        Place place = new Place();
        City city = new City();
        if (Convert.ToInt32(ddlCity.SelectedIndex) != 0)
        {
            city.Id = Convert.ToInt32(ddlCity.SelectedValue);
            place.City = city;
            ddlPlace.DataSource = placeController.GetPlacesByCity(place.City);
            ddlPlace.DataTextField = "Address";
            ddlPlace.DataValueField = "Id";
            ddlPlace.DataBind();
            ddlPlace.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlPlace();
        }
    }

    private void ClearDdlPlace()
    {
        for (int i = 0; i < ddlPlace.Items.Count; i++)
        {
            ddlPlace.Items[i].Selected = false;
        }
        ddlPlace.DataSource = "";
        ddlPlace.DataBind();
    }

    private void FillDdlCity()
    {
        CityController cityController = new CityController();
        City city = new City();
        State state = new State();
        if (Convert.ToInt32(ddlState.SelectedIndex) != 0)
        {
            state.Id = Convert.ToInt32(ddlState.SelectedValue);
            city.State = state;
            ddlCity.DataSource = cityController.listCityByState(state);
            ddlCity.DataTextField = "Description";
            ddlCity.DataValueField = "Id";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlCity();
            ClearDdlPlace();
        }
    }

    private void ClearDdlCity()
    {
        for (int i = 0; i < ddlCity.Items.Count; i++)
        {
            ddlCity.Items[i].Selected = false;
        }
        ddlCity.Items[0].Selected = true;
        ddlCity.DataSource = "";
        ddlCity.DataBind();
    }

    private void FillDdlState()
    {
        StateController stateController = new StateController();
        ddlState.DataSource = stateController.GetStates();
        ddlState.DataTextField = "Acronym";
        ddlState.DataValueField = "Id";
        ddlState.DataBind();
        ddlState.Items.Insert(0, "Selecione");
    }

    private void FillData()
    {
        string id = Session[UnitConstants.SESSION_UNIT_ID].ToString();
        br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
        UnitController unitController = new UnitController();
        unit.Id = Convert.ToInt32(id);
        unit = unitController.GetUnit(unit);
        PlaceController placeController = new PlaceController();
        Place place = new Place();
        place.Id = unit.Place.Id;
        City city = new City();
        CityController cityController = new CityController();
        State state = new State();
        StateController stateController = new StateController();
        place = placeController.GetPlace(place.Id);
        city = cityController.SelectCity(place.City);
        state = stateController.GetState(city.State.Id);
        try
        {
            MatchDdlStateValue(state);
            FillDdlCity();
            MatchDdlCityValue(city);
            FillDdlPlace();
            MatchDdlPlaceValue(place);
            txbName.Text = unit.Name.Trim();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento dos valores: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private void MatchDdlStateValue(State state)
    {
        ListItem listState = ddlState.Items.FindByValue(Convert.ToString(state.Id));
        for (int i = 0; i < ddlState.Items.Count; i++)
        {
            ddlState.Items[i].Selected = false;
        }
        if (listState != null)
        {
            listState.Selected = true;
        }
        else
        {
            ddlState.Items[0].Selected = true;
        }
    }

    private void MatchDdlPlaceValue(Place place)
    {
        ListItem listPlace = ddlPlace.Items.FindByValue(Convert.ToString(place.Id));
        for (int i = 0; i < ddlPlace.Items.Count; i++)
        {
            ddlPlace.Items[i].Selected = false;
        }
        if (listPlace != null)
        {
            listPlace.Selected = true;
        }
        else
        {
            ddlPlace.Items[0].Selected = true;
        }
    }

    private void MatchDdlCityValue(City city)
    {
        ListItem listCity = ddlCity.Items.FindByValue(Convert.ToString(city.Id));

        for (int i = 0; i < ddlCity.Items.Count; i++)
        {
            ddlCity.Items[i].Selected = false;
        }
        if (listCity != null)
        {
            listCity.Selected = true;
        }
        else
        {
            ddlCity.Items[0].Selected = true;
        }
    }

    protected void txbUpdate_Click(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Unit unitUpdate = new br.com.SistemaChamados.Model.Unit();
        UnitController Controller = new UnitController();
        if (validateFields())
        {
            try
            {
                EnumCRUDState resultOperation = Controller.UpdateUnit(populateObject(unitUpdate));
                if (resultOperation == EnumCRUDState.SQL_SUCCESS)
                {
                    Response.Write(@"<script language='javascript'>alert('Unidade atualizada com sucesso!');</script>");
                    ClearFields();
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a correção, por favor tente novamente!');</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na correção: <br>" + ex.Message +
                                   ".');</script>");
                unitUpdate = null;
            }
            finally
            {
                Response.Redirect("UnitMain.aspx");
                Session.Remove(UnitConstants.SESSION_UNIT_ID);

            }
        }
    }
    
    private br.com.SistemaChamados.Model.Unit populateObject(br.com.SistemaChamados.Model.Unit unitUpdate)
    {
        string id = Session[UnitConstants.SESSION_UNIT_ID].ToString();
        unitUpdate.Id = Convert.ToInt32(id);
        unitUpdate.Name = txbName.Text;
        Place placeToUnit = new Place();
        placeToUnit.Id = Convert.ToInt32(ddlPlace.SelectedValue);
        unitUpdate.Place = placeToUnit;
        return unitUpdate;
    }

    private bool validateFields()
    {
        bool isValid = false;
        if (ddlState.SelectedIndex == 0)
        {
            Response.Write(@"<script language='javascript'>alert('Selecione um estado');</script>");
            ddlState.Focus();
        }
        else
        {
            if (ddlCity.SelectedIndex == 0)
            {
                Response.Write(@"<script language='javascript'>alert('Selecione uma cidade');</script>");
                ddlCity.Focus();
            }
            else
            {
                if (ddlPlace.SelectedIndex == 0)
                {
                    Response.Write(@"<script language='javascript'>alert('Selecione um lugar');</script>");
                    ddlPlace.Focus();
                }
                else
                {
                    isValid = true;
                }
            }
         }
        return isValid;
    }

    public void ClearFields()
    {
        txbName.Text = "";
        txbName.Focus();
    }

    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlCity();
    }

    protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlPlace();
    }

}